package com.activemq.retry;

import cn.hutool.core.date.DateUtil;
import com.activemq.cluster.ClusterProd;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.RedeliveryPolicy;
import org.springframework.context.ApplicationContext;

import javax.jms.*;
import java.util.UUID;

public class RetrySender {
    public static void main(String[] args) throws Exception {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(ClusterProd.CLUSTER_URL);
        try (Connection connection = factory.createConnection()) {
            connection.start();
            try (Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                 MessageProducer producer = session.createProducer(session.createQueue(ClusterProd.QUEUE_NAME))) {
                for (int i = 0; i < 3; i++) {
                    producer.send(session.createTextMessage("发送消息" + DateUtil.now() + "_" + UUID.randomUUID()));
                }
            }
        }
    }
}

@Slf4j
class RetryRev {
    public static void main(String[] args) throws Exception {

        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(ClusterProd.CLUSTER_URL);
        //最多重重试3次
        RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
        redeliveryPolicy.setMaximumRedeliveryDelay(2);
        factory.setRedeliveryPolicy(redeliveryPolicy);
        try (Connection connection = factory.createConnection()) {
            connection.start();
            try (Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
                 MessageConsumer consumer = session.createConsumer(session.createQueue(ClusterProd.QUEUE_NAME))) {
                consumer.setMessageListener((msg) -> {
                    try {
                        log.info("接收到消息了！" + ((TextMessage) msg).getText());
                    } catch (JMSException e) {
                        log.error("接受消息失败，原因", e);
                    }
                });
                System.in.read();
            }
        }
    }
}